package edu.zjgsu.ito.service.Impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import edu.zjgsu.ito.service.IFileService;
import edu.zjgsu.ito.utils.Constant;
import edu.zjgsu.ito.utils.FileUtil;

@Service
@Transactional
public class FileServiceImpl implements IFileService {

	public String uploadHead(MultipartFile image) {
		// 获取图片后缀名
		String extension = FileUtil.getExtension(image.getOriginalFilename());
		
		// 合法的图片后缀名
		String[] invalidExt = {".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".gif"};
		
		int i = 0;
		for(; i < invalidExt.length; i++) {
			if(extension.equals(invalidExt[i])) {
				break;
			}
		}
		
		if(i == invalidExt.length) {
			throw new RuntimeException("图片格式不正确");
		}
		
		
		String webrootPath = this.getClass().getResource("/").getPath().substring(1).substring(0, this.getClass().getResource("/").getPath().substring(1).indexOf("WEB-INF"));
		/* 解决路径中有空格的问题 */
		try {
			webrootPath = URLDecoder.decode(webrootPath, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String path = FileUtil.getPath(webrootPath.replaceAll("partywork", "upload").replaceAll("partyBuilding", "upload")+"photo/", image.getOriginalFilename());
		
		//System.out.println("=========================" + path);
		
		try {
			FileUtil.saveFile(image, path);
		} catch (IOException e) {
			throw new RuntimeException("图片上传失败");
		}
		
		return path.substring(Constant.UPLOAD_DIR.length());
	}
	
	public String uploadVideo(MultipartFile video) {
		// 获取视频后缀名
		String extension = FileUtil.getExtension(video.getOriginalFilename());
		
		// 合法的视频后缀名
		String[] invalidExt = {".mp4"};
		
		int i = 0;
		for(; i < invalidExt.length; i++) {
			if(extension.equals(invalidExt[i])) {
				break;
			}
		}
		
		if(i == invalidExt.length) {
			throw new RuntimeException("视频格式不正确");
		}
		
		
		String webrootPath = this.getClass().getResource("/").getPath().substring(1).substring(0, this.getClass().getResource("/").getPath().substring(1).indexOf("WEB-INF"));
		/* 解决路径中有空格的问题 */
		try {
			webrootPath = URLDecoder.decode(webrootPath, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String path = FileUtil.getPath(webrootPath.replaceAll("partywork", "upload").replaceAll("partyBuilding", "upload")+"video/", video.getOriginalFilename());
		
		//System.out.println("=========================" + path);
		
		try {
			FileUtil.saveFile(video, path);
		} catch (IOException e) {
			throw new RuntimeException("视频上传失败");
		}
		
		return path.substring(Constant.UPLOAD_DIR.length());
	}

}
